package review.organization.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import review.dao.*;
import review.entity.*;
import review.entity.model.SpecialistModel;
import review.system.service.CompanyService;
import review.system.service.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class SpecialistServiceImpl implements SpecialistService {

  @Autowired
  private SpecialistDAO specialistDAO;

  @Autowired
  private CompanyDAO companyDAO;

  @Autowired
  private TitleLevelDAO titleLevelDAO;

  @Autowired
  private ScienceDAO scienceDAO;

  @Autowired
  private JobDAO jobDAO;

  @Autowired
  private CompanyService companyService;

  @Autowired
  private UserDAO userDAO;

  @Autowired
  private UserService userService;

  // 添加专家
  public void addSpecialist(SpecialistModel model) {
    if (!StringUtils.hasText(model.getName())) {
      throw new RuntimeException("姓名为空");
    }
    List<Users> usersList = userDAO.findByUsername(model.getUser());
    if (usersList.isEmpty()) {
      throw new RuntimeException("该用户名不存在");
    }
    if (!StringUtils.hasText(model.getCompany())) {
      throw new RuntimeException("单位为空");
    }
    Specialist specialist = new Specialist();
    // 添加姓名
    specialist.setName(model.getName());
    // 获取登录用户的ID
    Integer userId = userService.getLoginId();
    specialist.setUserId(userId);
    // 获取用户名的ID
    for (Users users : usersList) {
      Specialist sp = specialistDAO.findBySpecialistId(users.getId());
      if (sp != null) {
        throw new RuntimeException("该用户名以被绑定");
      } else {
        specialist.setSpecialistId(users.getId());
      }
    }
    Specialist s = judgeexist(model, specialist);
    specialistDAO.save(s);
  }

  // 修改专家
  public void updateSpecialist(SpecialistModel model) {
    Specialist specialist = new Specialist();
    if (model.getId() == null) {
      throw new RuntimeException("该ID专家不存在");
    }
    Specialist s = judgeexist(model, specialist);
    if (model.getName() != null) {
      s.setId(model.getId());
    }
    s.setName(model.getName());
    specialistDAO.save(s);
  }

  // 判断属性是否存在
  public Specialist judgeexist(SpecialistModel model, Specialist specialist) {
    // 单位
    // 查询单位是否存在
    Company company = companyDAO.findByName(model.getCompany());
    if (company == null) {
      // 单位不存在则创建一个
      Company c = new Company();
      c.setName(model.getCompany());
      companyService.addCompany(c);
    }
    // 添加单位id
    Company co = companyDAO.findByName(model.getCompany());
    specialist.setCompanyId(co.getId());
    // 职称
    // 查询职称是否存在
    TitleLevel titleLevel = titleLevelDAO.findByName(model.getTitle());
    if (titleLevel == null) {
      specialist.setTitleId(null);
    } else {
      specialist.setTitleId(titleLevel.getId());
    }
    // 专业
    Science science = scienceDAO.findByName(model.getScience());
    if (science == null) {
      specialist.setScienceId(null);
    } else {
      specialist.setScienceId(science.getId());
    }
    // 职务
    Job job = jobDAO.findByName(model.getJob());
    if (job == null) {
      specialist.setJobId(null);
    } else {
      specialist.setJobId(job.getId());
    }
    return specialist;
  }

  // 删除专家
  public void deleteSpecialist(Specialist specialist) {
    if (specialist.getId() == null) {
      throw new RuntimeException("ID为空");
    }
    Specialist sp = judge(specialist);
    specialistDAO.delete(sp);
  }

  // 判断ID是否存在
  public Specialist judge(Specialist specialist) {
    Optional<Specialist> o = specialistDAO.findById(specialist.getId());
    if (!o.isPresent()) {
      throw new RuntimeException("ID不存在");
    } else {
      return o.get();
    }
  }

  // 分页查询
  public Page<SpecialistModel> findAll(int page, int sise, Specialist specialist) {
    ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues().withMatcher("nmae",
        ExampleMatcher.GenericPropertyMatchers.contains());
    Example<Specialist> example = Example.of(specialist, matcher);
    Pageable pageable = PageRequest.of(page - 1, sise, Sort.by(Sort.Direction.ASC, "id"));
    Page<Specialist> specialistPage = specialistDAO.findAll(example, pageable);
    List<Specialist> list = specialistPage.getContent();
    List<SpecialistModel> modelList = new ArrayList<>();
    for (Specialist s : list) {
      SpecialistModel model = updateModel(s);
      modelList.add(model);
    }
    // 将List转换为Page
    Page<SpecialistModel> modelPage = new PageImpl<SpecialistModel>(modelList, pageable,
        specialistPage.getTotalElements());
    return modelPage;
  }

  // 查询全部
  public List<SpecialistModel> findAll() {
    List<Specialist> list = specialistDAO.findAll();
    List<SpecialistModel> modelList = new ArrayList<>();
    for (Specialist s : list) {
      SpecialistModel model = updateModel(s);
      modelList.add(model);
    }
    return modelList;
  }

  // 根据Specialist生成SpecialistModel
  public SpecialistModel updateModel(Specialist specialist) {
    SpecialistModel specialistModel = new SpecialistModel();
    // 姓名
    specialistModel.setName(specialist.getName());
    // 单位
    if (specialist.getCompanyId() != null) {
      Optional<Company> company = companyDAO.findById(specialist.getCompanyId());
      if (company.isPresent()) {
        specialistModel.setCompany(company.get().getName());
        specialistModel.setCompanyId(specialist.getCompanyId());
      }
    }
    // 职称
    if (specialist.getTitleId() != null) {
      Optional<TitleLevel> titleLevel = titleLevelDAO.findById(specialist.getTitleId());
      if (titleLevel.isPresent()) {
        specialistModel.setTitle(titleLevel.get().getName());
        specialistModel.setTitleId(specialist.getTitleId());
      }
    }
    // 专业
    if (specialist.getScienceId() != null) {
      Optional<Science> science = scienceDAO.findById(specialist.getScienceId());
      if (science.isPresent()) {
        specialistModel.setScience(science.get().getName());
        specialistModel.setScienceId(specialist.getScienceId());
      }
    }
    // 职务
    if (specialist.getJobId() != null) {
      Optional<Job> job = jobDAO.findById(specialist.getJobId());
      if (job.isPresent()) {
        specialistModel.setJob(job.get().getName());
        specialistModel.setJobId(specialist.getJobId());
      }
    }
    // 用户名
    if (specialist.getSpecialistId() != null) {
      Optional<Users> users = userDAO.findById(specialist.getSpecialistId());
      if (users.isPresent()) {
        specialistModel.setUser(users.get().getUsername());
      }
    }
    return specialistModel;
  }
}
